﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Documents;
using System.Xml.Linq;
using Microsoft.Office.Interop.Word;
using Application = Microsoft.Office.Interop.Word.Application;

namespace ProjectWizardManagementv1.Infrastructure.Concrete
{
    public static class WordDocxDocumentIO
    {
        public static XElement ReadDocument(string path)
        {
            var package = Package.Open(path);
            var docUri = new Uri("/word/document.xml", UriKind.Relative);
            var documentPart = package.GetPart(docUri);
            return XElement.Load(new StreamReader(documentPart.GetStream()));
        }

        public static void SaveDocument(TextRange textRange, string path)
        {
            var tempFileLocation = string.Format(@"{0}", path.Replace(".docx", ".tmp"));
            var fileStream = new FileStream(tempFileLocation, FileMode.Create);
            textRange.Save(fileStream, DataFormats.Rtf);
            fileStream.Close();

            var wordApp = new Application();
            wordApp.Documents.Add(tempFileLocation);
            var document = wordApp.ActiveDocument;

            document.SaveAs(path, WdSaveFormat.wdFormatDocumentDefault);
            wordApp.Quit(WdSaveOptions.wdSaveChanges);
            File.Delete(tempFileLocation);
        }
    }
}
